package com.turato.table.factory;

import com.turato.table.service.MsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author tuhao
 * @date 2021/1/16 5:06 下午
 * @desc MsgService 工厂，管理
 */
@Component
@Slf4j
public class MsgMapFactory {

    private Map<String, MsgService> msgServiceMap;

    /**
     * 注入：通过spring容器将所有实现 MsgService 接口的类的实例注入到 serviceList 中
     */
    @Autowired
    private List<MsgService> serviceList;


    /**
     * 通过 @PostConstruct 注解，在 MsgMapFactory 实例化后，来初始化 msgServiceMap
     *
     */

    @PostConstruct
    private void init() {
        if (CollectionUtils.isEmpty(serviceList)) {
            return;
        }
        msgServiceMap = new HashMap<String, MsgService>();
        for (MsgService msgService : serviceList) {
            if (null != msgServiceMap.get(msgService.getChannelType())) {
                log.info("重复加载{}MsgService", msgService.getChannelType());
            } else {
                msgServiceMap.put(msgService.getChannelType(), msgService);
            }
        }
    }

    public MsgService buildMsgService(String channelType) {
        return msgServiceMap.get(channelType);
    }
}
